package com.zx._06_JVM;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @version v1.0
 *         计算机配置 英特尔 i7-5500U, 64位, win10, JVM为模式状态
 *
 *         测试结果：
 *         混合模式：jvm参数是  -Xmixed， 程序运行时间：2514 us
 *         编译模式：jvm参数是  -Xcomp，   程序运行时间：3403 us
 *         解释模式：jvm参数是  -Xint，     程序运行时间：8561 us
 * @Title: JvmWordModel
 * @Description: java 三种工作模式（本程序只是单纯的想要模拟频繁调用方法的场景）
 * @author: xue.zhang
 * @date: 2018年6月17日下午5:15:24
 * @company: yooli
 * @Copyright: Copyright (c) 2017
 */
public class JvmWordModel {

    private static AtomicLong time = new AtomicLong(0);

    public static void main(String[] args) throws InterruptedException {
        int testNum = 1000;
        for (int i = 0; i < testNum; i++) {// 测试1000次
            Thread thread = new Thread(new Job());
            thread.start();
            thread.join();
        }
        System.out.println(time.get() / 1000 / testNum + " us,avg");
    }

    public static class Job implements Runnable {

        @Override
        public void run() {
            int number = 8;
            int iterationNumber = 20000;
            CountDownLatch countDownLatch = new CountDownLatch(number);
            Obj[] objArray = new Obj[number];
            for (int i = 0; i < number; i++) {
                objArray[i] = new Obj();
            }

            long start = System.nanoTime();
            for (int i = 0; i < number; i++) {
                int ii = i;
                Thread thread = new Thread(new Runnable() {
                    int iterationNumberInner = iterationNumber;

                    @Override
                    public void run() {
                        while (iterationNumberInner-- > 0) {
                            objArray[ii].aLong += 1L;
                        }
                        countDownLatch.countDown();
                    }
                });
                thread.start();
            }
            try {
                countDownLatch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            long end = System.nanoTime();
            time.getAndAdd(end - start);
        }
    }

    private static final class Obj {

        private volatile long aLong = 8L;
    }
}
